<template>
    <div class="news-pool-container">
        <h2 class="page-title">news.pool</h2>

        <div class="layout-wrapper">
            <!-- 左侧新闻池区域 -->
            <div class="left-column">
                <div class="content-wrapper">
                    <!-- 搜索、类型、筛选行 -->
                    <div class="search-row">
                        <label class="search-label">新闻内容：</label>
                        <el-input v-model="keywords" placeholder="请输入文章摘要或新闻标题" style="width: 280px"
                            @keyup.enter="handleSearch"></el-input>
                        <el-button type="primary" @click="handleSearch" style="margin-left: 10px">搜索</el-button>
                        <el-button @click="handleReset" style="margin-left: 10px">重置</el-button>
                        <!-- 仅-admin用户显示手动添加按钮 -->
                        <el-button 
                            type="primary" 
                            @click="openAddDialog" 
                            style="margin-left: 10px"
                            v-if="isAdminUser"
                        >
                            手动添加
                        </el-button>
                    </div>

                    <div class="type-row">
                        <label class="type-label">新闻类型：</label>
                        <el-tag v-for="(type, index) in typeList" :key="index" :class="{
                            'highlight-tag': type.classReal === selectedClassReal,
                            'default-all-tag': type.classReal === 'all' && type.classReal === selectedClassReal,
                        }" @click="handleTypeChange(type.classReal)"
                            style="margin-right: 8px; cursor: pointer; margin-bottom: 8px">
                            {{ type.className }} ({{ type.count }})
                        </el-tag>
                    </div>

                    <div class="filter-row">
                        <label class="filter-label">筛选条件：</label>
                        <el-select v-model="sortOrder" placeholder="排序方式" style="width: 140px; margin-right: 10px"
                            @change="handleFilterChange">
                            <el-option label="创建时间降序" value="desc"></el-option>
                            <el-option label="创建时间升序" value="asc"></el-option>
                        </el-select>

                        <el-select v-model="timeRangeType" placeholder="时间范围" style="width: 120px; margin-right: 10px"
                            @change="handleTimeRangeChange">
                            <el-option label="全部" value="all"></el-option>
                            <el-option label="一周内" value="oneWeek"></el-option>
                            <el-option label="自定义" value="custom"></el-option>
                        </el-select>

                        <el-select v-model="addMode" placeholder="添加方式" style="width: 120px; margin-right: 10px"
                            @change="handleFilterChange">
                            <el-option label="全部" value="all"></el-option>
                            <el-option label="手动（人工）" value="1"></el-option>
                            <el-option label="自动" value="0"></el-option>
                        </el-select>

                        <el-select v-model="isPublished" placeholder="发布状态" style="width: 120px"
                            @change="handleFilterChange">
                            <el-option label="全部" value="all"></el-option>
                            <el-option label="已发布" value="1"></el-option>
                            <el-option label="待发布" value="0"></el-option>
                        </el-select>
                    </div>

                    <!-- 自定义时间显示 -->
                    <div v-if="timeRangeType === 'custom' && customTimeRange.length === 2" class="custom-time-display">
                        <span class="time-display-label">已选择时间范围：</span>
                        <span class="time-display-value">{{ formatDisplayTime(customTimeRange[0]) }} 至 {{
                            formatDisplayTime(customTimeRange[1]) }}</span>
                        <el-button type="text" @click="clearCustomTime" style="margin-left: 10px">清除</el-button>
                    </div>

                    <!-- 新闻表格 -->
                    <el-table :data="newsList" border style="width: 100%; margin-top: 20px" v-loading="loading"
                        empty-text="暂无匹配的新闻数据" highlight-current-row @row-click="handleRowClick">
                        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
                        <el-table-column prop="title" label="标题" min-width="220"
                            show-overflow-tooltip></el-table-column>
                        <el-table-column prop="abstractReal" label="摘要" min-width="250"
                            show-overflow-tooltip></el-table-column>
                        <el-table-column label="新闻类型" width="140" align="center">
                            <template #default="scope">
                                {{ classRealMap[scope.row.classReal] || '未分类' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="newsSource" label="来源" width="120" align="center"></el-table-column>
                        <el-table-column prop="newsTime" label="新闻时间" width="140" align="center"></el-table-column>
                        <el-table-column prop="addMode" label="添加方式" width="120" align="center"
                            :formatter="formatAddMode"></el-table-column>
                        <el-table-column prop="isPublished" label="发布状态" width="120" align="center"
                            :formatter="formatPublishStatus"></el-table-column>
                        <el-table-column prop="createTime" label="创建时间" width="160" align="center"></el-table-column>
                        <el-table-column label="操作" width="200" align="center">
                            <template #default="scope">
                                <!-- 仅-admin用户显示编辑按钮 -->
                                <el-button 
                                    type="primary" 
                                    link 
                                    @click="handleEdit(scope.row)"
                                    v-if="isAdminUser"
                                >
                                    编辑
                                </el-button>
                                <el-button type="primary" link @click="handleAddToPublish(scope.row)">加入待发布</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 分页组件 -->
                    <div class="pagination-container" style="margin-top: 15px; text-align: right">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                            :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            background></el-pagination>
                    </div>
                </div>
            </div>

            <!-- 右侧待发布区域 -->
            <div class="right-column">
                <div class="content-wrapper">
                    <!-- 固定标题和分类筛选区 -->
                    <div class="to-publish-header">
                        <h3 class="to-publish-title">待发布新闻 ({{ toPublishTotal }})</h3>
                        <!-- 待发布分类标签 -->
                        <div class="to-publish-type">
                            <el-tag v-for="(type, index) in toPublishTypeList" :key="index" class="type-tag"
                                :class="{ 'active-tag': type.classReal === toPublishType }"
                                @click="handleToPublishTypeChange(type.classReal)">
                                {{ type.className }} ({{ type.count }})
                            </el-tag>
                        </div>
                    </div>

                    <!-- 固定高度的可滚动内容区 -->
                    <div class="to-publish-scroll-container">
                        <!-- 待发布新闻列表 -->
                        <el-card v-for="(item, index) in filteredToPublishList" :key="item.id" class="to-publish-card"
                            v-loading="toPublishLoading">
                            <!-- 左上角新闻类型标签 -->
                            <div class="news-type-tag" :style="{ backgroundColor: getTypeColor(item.classReal) }">
                                {{ getTypeName(item.classReal) }}
                            </div>

                            <div class="card-header">
                                <span class="card-title">{{ item.title }}</span>
                            </div>

                            <div class="card-content">
                                {{ item.abstractReal }}
                            </div>

                            <div class="card-footer">
                                <div class="footer-info">
                                    <span>{{ item.newsSource }}</span>
                                    <span>由{{ item.addUser || '系统' }}添加</span>
                                </div>
                                <!-- 移除和编辑按钮 -->
                                <div class="footer-actions">
                                    <el-button type="text" @click="handleRemoveToPublish(item)"
                                        class="remove-btn">移除</el-button>
                                    <!-- 仅-admin用户显示编辑按钮 -->
                                    <el-button 
                                        type="text" 
                                        @click="handleEditToPublish(item)"
                                        v-if="isAdminUser"
                                    >
                                        编辑
                                    </el-button>
                                </div>
                            </div>
                        </el-card>
                        <el-empty v-if="!toPublishLoading && filteredToPublishList.length === 0"
                            description="暂无待发布新闻"></el-empty>
                    </div>

                    <!-- 发布设置按钮（带跳转逻辑） -->
                    <div class="to-publish-footer">
                        <el-button type="primary" class="publish-setting-btn"
                            @click="handleGoToPublishSetting">发布设置</el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 时间选择弹窗 -->
        <el-dialog v-model="customTimeVisible" title="选择时间范围" width="500px" :modal="true" :close-on-click-modal="false"
            :destroy-on-close="true">
            <div class="custom-time-picker">
                <el-date-picker v-model="tempCustomTimeRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"
                    value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                <p class="time-tip">提示：支持选择任意时间段，时间格式为 YYYY-MM-DD HH:mm:ss</p>
            </div>
            <template #footer>
                <el-button @click="handleCancelCustomTime">取消</el-button>
                <el-button type="primary" @click="confirmCustomTime">确认</el-button>
            </template>
        </el-dialog>

        <!-- 编辑/添加弹窗 -->
        <el-dialog v-model="editVisible" :title="''" width="100%" height="100%" :fullscreen="false" :modal="false"
            :close-on-click-modal="false" :before-close="handleEditClose" :custom-class="'edit-dialog-full'"
            :show-close="false">
            <div class="custom-mask" @click="editVisible = false"></div>
            <div class="edit-content-wrapper">
                <div class="edit-header">
                    <h2>{{ isAdd ? '添加新闻' : '编辑新闻' }}</h2>
                    <el-button icon="Close" circle @click="editVisible = false" class="close-btn"></el-button>
                </div>
                <div class="edit-body">
                    <div class="edit-layout">
                        <div class="edit-form-container">
                            <el-form label-width="100px" :model="editForm" :rules="editRules" ref="editFormRef">
                                <el-form-item label="新闻标题" prop="title">
                                    <el-input v-model="editForm.title" type="textarea" :rows="2"
                                        placeholder="请输入新闻标题" />
                                </el-form-item>
                                <el-form-item label="新闻标签" prop="classReal">
                                    <el-select v-model="editForm.classReal" placeholder="请选择新闻标签">
                                        <el-option v-for="(type, index) in typeList.filter(t => t.classReal !== 'all')"
                                            :key="index" :label="type.className" :value="type.classReal" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="新闻来源" prop="siteName">
                                    <el-input v-model="editForm.siteName" placeholder="请输入新闻来源" />
                                </el-form-item>
                                <el-form-item label="新闻网址" prop="sourceUrl">
                                    <el-input v-model="editForm.sourceUrl" placeholder="请输入新闻网址" />
                                </el-form-item>
                                <el-form-item label="新闻摘要" prop="abstractReal">
                                    <el-input v-model="editForm.abstractReal" type="textarea" :rows="6"
                                        placeholder="请输入新闻摘要" />
                                </el-form-item>
                                <el-form-item label="新闻时间" prop="newsTime">
                                    <el-date-picker v-model="editForm.newsTime" type="datetime"
                                        value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择新闻时间" style="width: 100%" />
                                </el-form-item>
                                <el-form-item label="正文内容" prop="markContent">
                                    <el-input v-model="editForm.markContent" type="textarea" :rows="10"
                                        placeholder="请输入正文内容" />
                                </el-form-item>
                            </el-form>
                        </div>
                        <div class="edit-content-container">
                            <div class="content-header">内容预览</div>
                            <div class="mark-content">
                                <pre v-if="editForm.markContent" class="content-pre">{{ editForm.markContent }}</pre>
                                <p v-else class="no-content">暂无内容</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="edit-footer">
                    <el-button @click="editVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveEdit">确定</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 详情弹窗 -->
        <el-dialog v-model="detailVisible" :title="''" width="100%" height="100%" :fullscreen="false" :modal="false"
            :close-on-click-modal="false" :before-close="handleDetailClose" :custom-class="'detail-dialog-full'"
            :show-close="false">
            <div class="custom-mask" @click="detailVisible = false"></div>
            <div class="detail-content-wrapper">
                <div class="detail-header">
                    <h2>详情</h2>
                    <el-button icon="Close" circle @click="detailVisible = false" class="close-btn"></el-button>
                </div>
                <div class="detail-body">
                    <div class="detail-top">
                        <h3>{{ detailForm.title }}</h3>
                        <div class="detail-info">
                            <span>{{ detailForm.newsSource }}</span>
                            <span>{{ detailForm.newsTime }}</span>
                            <a :href="detailForm.sourceUrl" target="_blank" v-if="detailForm.sourceUrl">原文链接</a>
                        </div>
                        <div class="detail-abstract-container">
                            <div class="detail-abstract" :class="{ 'expanded': isAbstractExpanded }">
                                {{ detailForm.abstractReal }}
                            </div>
                            <el-button 
                                type="text" 
                                @click="isAbstractExpanded = !isAbstractExpanded"
                                v-if="hasLongAbstract"
                                class="toggle-abstract-btn"
                            >
                                {{ isAbstractExpanded ? '收起' : '展开' }}
                            </el-button>
                        </div>
                    </div>
                    <div class="detail-bottom">
                        <div class="mark-content">
                            <pre v-if="detailForm.markContent" class="content-pre">{{ detailForm.markContent }}</pre>
                            <p v-else class="no-content">暂无正文内容</p>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useRouter } from 'vue-router' 

// 路由实例
const router = useRouter()

// 新闻类型配置（含颜色映射）
const newsTypes = [
    { color: '#83DAAD', label: '宏观形势', value: 1, key: 'macroEnvironment' },
    { color: '#EDBF45', label: '行业动态', value: 2, key: 'industryTrends' },
    { color: '#8E63B7', label: '产业链动态', value: 3, key: 'supplyChainDynamics' },
    { color: '#E8954F', label: '国际能源观察', value: 4, key: 'internationalEnergy' },
    { color: '#697798', label: '其他', value: 0, key: 'other' },
]

// 左侧数据和逻辑
const classRealMap = ref({
    1: '宏观形势',
    2: '行业动态',
    3: '产业链动态',
    4: '国际能源观察',
    5: '其他'
})

// 权限控制：判断是否为-admin用户
const currentUser = ref('') // 假设从登录状态获取用户名
const isAdminUser = computed(() => {
    // 实际项目中应从登录状态管理（如Pinia/Vuex）获取用户名
    return currentUser.value && currentUser.value.endsWith('-admin')
})

// 筛选参数 - 初始化默认值，避免 null/undefined
const keywords = ref('')
const selectedClassReal = ref('all')
const sortOrder = ref('desc') // 默认降序
const timeRangeType = ref('all')
const customTimeRange = ref([])
const tempCustomTimeRange = ref([])
const customTimeVisible = ref(false)
const addMode = ref('all')
const isPublished = ref('all')

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据存储
const newsList = ref([])
const localNewsList = ref([]) // 本地存储的手动添加新闻
const typeList = ref([
    { classReal: 'all', className: '全部', count: 0 },
    { classReal: '1', className: '宏观形势', count: 0 },
    { classReal: '2', className: '行业动态', count: 0 },
    { classReal: '3', className: '产业链动态', count: 0 },
    { classReal: '4', className: '国际能源观察', count: 0 },
    { classReal: '5', className: '其他', count: 0 }
])
const loading = ref(false)

// 右侧待发布相关数据
const toPublishList = ref([])
const toPublishTotal = ref(0)
const toPublishType = ref('all')
const toPublishTypeList = ref([
    { classReal: 'all', className: '全部', count: 0 },
    { classReal: '1', className: '宏观形势', count: 0 },
    { classReal: '2', className: '行业动态', count: 0 },
    { classReal: '3', className: '产业链动态', count: 0 },
    { classReal: '4', className: '国际能源观察', count: 0 },
    { classReal: '5', className: '其他', count: 0 }
])
const toPublishLoading = ref(false)

// 编辑/添加弹窗相关
const editVisible = ref(false)
const isAdd = ref(false) // 标记是添加还是编辑
const editForm = reactive({
    id: '',
    title: '',
    classReal: '',
    siteName: '',
    sourceUrl: '',
    abstractReal: '',
    newsTime: '',
    markContent: '',
    addMode: 1, // 手动添加
    isPublished: 0 // 默认待发布
})
const editRules = reactive({
    title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
    classReal: [{ required: true, message: '请选择新闻标签', trigger: 'change' }],
    abstractReal: [{ required: true, message: '请输入新闻摘要', trigger: 'blur' }],
    newsTime: [{ required: true, message: '请选择新闻时间', trigger: 'change' }],
    markContent: [{ required: true, message: '请输入正文内容', trigger: 'blur' }]
})
const editFormRef = ref(null)

// 详情弹窗相关
const detailVisible = ref(false)
const detailForm = ref({
    title: '',
    newsSource: '',
    newsTime: '',
    sourceUrl: '',
    abstractReal: '',
    markContent: ''
})
const isAbstractExpanded = ref(false)

// 判断摘要是否过长（超过一行）
const hasLongAbstract = computed(() => {
    return detailForm.value.abstractReal && detailForm.value.abstractReal.length > 40
})

// 工具函数
const cleanParams = (params) => {
    const cleaned = {}
    Object.keys(params).forEach(key => {
        if (params[key] !== 'all' && params[key] !== undefined && params[key] !== null && params[key] !== '') {
            cleaned[key] = params[key]
        }
    })
    return cleaned
}

const getInterfaceTimeRange = () => {
    if (timeRangeType.value === 'all') return null
    if (timeRangeType.value === 'oneWeek') {
        const now = new Date()
        const from = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        const formatTime = (date) => date.toISOString().slice(0, 19).replace('T', ' ')
        return `${formatTime(from)},${formatTime(now)}`
    }
    if (timeRangeType.value === 'custom' && customTimeRange.value && customTimeRange.value.length === 2) {
        return `${customTimeRange.value[0]},${customTimeRange.value[1]}`
    }
    return null
}

const formatDisplayTime = (timeStr) => {
    if (!timeStr) return ''
    return timeStr.split(' ')[0]
}

const formatDate = (date) => {
    return date.toISOString().slice(0, 19).replace('T', ' ')
}

// 生成唯一ID
const generateId = () => {
    return 'local_' + Date.now() + '_' + Math.floor(Math.random() * 1000)
}

// 本地存储操作
const saveLocalNews = () => {
    localStorage.setItem('manualNews', JSON.stringify(localNewsList.value))
}

const loadLocalNews = () => {
    const saved = localStorage.getItem('manualNews')
    if (saved) {
        try {
            localNewsList.value = JSON.parse(saved)
        } catch (error) {
            console.error('解析本地新闻失败:', error)
            localNewsList.value = []
        }
    }
}

// 合并接口数据和本地数据
const combineNewsData = (apiNews) => {
    const safeApiNews = Array.isArray(apiNews) ? apiNews : []
    const combined = [...safeApiNews]
    localNewsList.value.forEach(local => {
        const exists = combined.some(item => item.id === local.id)
        if (!exists) {
            combined.push(local)
        }
    })
    return combined
}

// 左侧接口调用
const fetchTypeStats = async () => {
    try {
        const timeRange = getInterfaceTimeRange()
        const params = {
            current: 1,
            currentSize: 10000,
            keywords: keywords.value || undefined,
            addMode: addMode.value !== 'all' ? addMode.value : undefined,
            isPublished: isPublished.value !== 'all' ? isPublished.value : undefined,
            timeRange: timeRange || undefined,
            sortby: 'createTime',
            sortOrder: sortOrder.value
        }
        const cleanedParams = cleanParams(params)

        const res = await request.get('/news/newsList', { params: cleanedParams })
        let allNews = res?.code === 200 ? (res.data?.records || []) : []
        
        allNews = combineNewsData(allNews)

        const countMap = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }

        allNews.forEach(news => {
            if (!news) return
            const real = news.classReal?.toString()
            if (['1', '2', '3', '4', '5'].includes(real)) {
                countMap[real]++
            }
        })

        const totalCount = Object.values(countMap).reduce((sum, val) => sum + val, 0)
        typeList.value = [
            { classReal: 'all', className: '全部', count: totalCount },
            { classReal: '1', className: '宏观形势', count: countMap['1'] },
            { classReal: '2', className: '行业动态', count: countMap['2'] },
            { classReal: '3', className: '产业链动态', count: countMap['3'] },
            { classReal: '4', className: '国际能源观察', count: countMap['4'] },
            { classReal: '5', className: '其他', count: countMap['5'] }
        ]
    } catch (error) {
        console.error('获取类型统计失败:', error)
    }
}

const fetchNews = async () => {
    loading.value = true
    try {
        const timeRange = getInterfaceTimeRange()
        const safeSortOrder = sortOrder.value || 'desc'
        const params = {
            current: currentPage.value,
            currentSize: pageSize.value,
            keywords: keywords.value || undefined,
            classReal: selectedClassReal.value !== 'all' ? selectedClassReal.value : undefined,
            addMode: addMode.value !== 'all' ? addMode.value : undefined,
            isPublished: isPublished.value !== 'all' ? isPublished.value : undefined,
            timeRange: timeRange || undefined,
            sortby: 'createTime',
            sortOrder: safeSortOrder
        }
        const cleanedParams = cleanParams(params)

        let apiNews = []
        let apiTotal = 0
        
        try {
            const res = await request.get('/news/newsList', { params: cleanedParams })
            if (res?.code === 200) {
                apiNews = res.data?.records || []
                apiTotal = res.data?.total || 0
            }
        } catch (error) {
            console.error('接口请求失败，仅显示本地数据:', error)
        }

        // 合并接口数据和本地数据
        const combinedNews = combineNewsData(apiNews)
        
        // 应用筛选条件到合并后的数据
        const filteredNews = combinedNews.filter(news => {
            if (!news) return false
            
            // 关键词筛选
            if (keywords.value && !(
                (news.title && news.title.includes(keywords.value)) ||
                (news.abstractReal && news.abstractReal.includes(keywords.value))
            )) {
                return false
            }
            
            // 类型筛选
            if (selectedClassReal.value !== 'all' && news.classReal?.toString() !== selectedClassReal.value) {
                return false
            }
            
            // 添加方式筛选
            if (addMode.value !== 'all' && news.addMode?.toString() !== addMode.value) {
                return false
            }
            
            // 发布状态筛选
            if (isPublished.value !== 'all' && news.isPublished?.toString() !== isPublished.value) {
                return false
            }
            
            // 时间范围筛选
            const newsTime = new Date(news.createTime || news.newsTime).getTime()
            if (timeRangeType.value === 'oneWeek') {
                const oneWeekAgo = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
                if (newsTime < oneWeekAgo) return false
            } else if (timeRangeType.value === 'custom' && customTimeRange.value && customTimeRange.value.length === 2) {
                const startTime = new Date(customTimeRange.value[0]).getTime()
                const endTime = new Date(customTimeRange.value[1]).getTime()
                if (newsTime < startTime || newsTime > endTime) return false
            }
            
            return true
        })

        // 排序
        filteredNews.sort((a, b) => {
            const timeA = new Date(a.createTime || a.newsTime).getTime()
            const timeB = new Date(b.createTime || b.newsTime).getTime()
            return safeSortOrder === 'desc' ? timeB - timeA : timeA - timeB
        })

        // 分页处理
        total.value = filteredNews.length
        const startIndex = Math.max(0, (currentPage.value - 1) * pageSize.value)
        const endIndex = startIndex + pageSize.value
        newsList.value = filteredNews.slice(startIndex, endIndex) || []

        if (currentPage.value === 1) {
            await fetchTypeStats()
        }
    } catch (error) {
        console.error('获取新闻失败:', error)
        newsList.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 右侧待发布初始化
const initToPublishList = async () => {
    toPublishLoading.value = true
    try {
        let apiToPublish = []
        try {
            const res = await request.post('/news/releaseList')
            if (res?.code === 200) {
                apiToPublish = res.data?.list || []
            }
        } catch (error) {
            console.error('获取接口待发布列表失败，使用本地存储:', error)
        }

        let localToPublish = []
        try {
            const saved = localStorage.getItem('toPublishNews')
            if (saved) {
                localToPublish = JSON.parse(saved)
            }
        } catch (error) {
            console.error('解析本地待发布列表失败:', error)
            localToPublish = []
        }
        
        const combined = [...apiToPublish]
        localToPublish.forEach(item => {
            const exists = combined.some(apiItem => apiItem.id === item.id)
            if (!exists) {
                combined.push(item)
            }
        })

        toPublishList.value = combined
        updateToPublishTypeStats()
    } catch (error) {
        console.error('初始加载待发布列表失败:', error)
    } finally {
        toPublishLoading.value = false
    }
}

// 保存待发布列表到本地
const saveToPublishList = () => {
    try {
        localStorage.setItem('toPublishNews', JSON.stringify(toPublishList.value))
    } catch (error) {
        console.error('保存待发布列表失败:', error)
        ElMessage.error('保存失败，请重试')
    }
}

// 更新待发布类型统计
const updateToPublishTypeStats = () => {
    const countMap = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
    toPublishList.value.forEach(item => {
        if (!item) return
        const real = item.classReal?.toString()
        if (['1', '2', '3', '4', '5'].includes(real)) {
            countMap[real]++
        }
    })

    const totalCount = Object.values(countMap).reduce((sum, val) => sum + val, 0)
    toPublishTypeList.value = [
        { classReal: 'all', className: '全部', count: totalCount },
        { classReal: '1', className: '宏观形势', count: countMap['1'] },
        { classReal: '2', className: '行业动态', count: countMap['2'] },
        { classReal: '3', className: '产业链动态', count: countMap['3'] },
        { classReal: '4', className: '国际能源观察', count: countMap['4'] },
        { classReal: '5', className: '其他', count: countMap['5'] }
    ]

    toPublishTotal.value = totalCount
}

// 待发布列表筛选
const filteredToPublishList = computed(() => {
    if (toPublishType.value === 'all') {
        return toPublishList.value
    }
    return toPublishList.value.filter(item => {
        if (!item) return false
        return item.classReal?.toString() === toPublishType.value.toString()
    })
})

// 获取新闻类型名称和颜色
const getTypeName = (classReal) => {
    const type = newsTypes.find(t => t.value.toString() === classReal?.toString())
    return type ? type.label : '未知类型'
}

const getTypeColor = (classReal) => {
    const type = newsTypes.find(t => t.value.toString() === classReal?.toString())
    return type ? type.color : '#ccc'
}

// 左侧交互
const handleTimeRangeChange = (value) => {
    if (value === 'custom') {
        if (customTimeRange.value && customTimeRange.value.length === 2) {
            tempCustomTimeRange.value = [...customTimeRange.value]
        } else {
            const now = new Date()
            const lastWeek = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
            tempCustomTimeRange.value = [formatDate(lastWeek), formatDate(now)]
        }
        customTimeVisible.value = true
    } else {
        handleFilterChange()
    }
}

const confirmCustomTime = () => {
    if (!tempCustomTimeRange.value || tempCustomTimeRange.value.length !== 2) {
        ElMessage.warning('请选择完整的时间范围')
        return
    }
    customTimeRange.value = [...tempCustomTimeRange.value]
    customTimeVisible.value = false
    handleFilterChange()
}

const handleCancelCustomTime = () => {
    customTimeVisible.value = false
    if (!customTimeRange.value || customTimeRange.value.length !== 2) {
        timeRangeType.value = 'all'
    }
}

const clearCustomTime = () => {
    customTimeRange.value = []
    timeRangeType.value = 'all'
    handleFilterChange()
}

// 打开添加弹窗（增加权限校验）
const openAddDialog = () => {
    if (!isAdminUser.value) {
        ElMessage.warning('仅管理员账号（后缀为-admin）可添加新闻')
        return
    }
    isAdd.value = true
    editForm.id = ''
    editForm.title = ''
    editForm.classReal = ''
    editForm.siteName = ''
    editForm.sourceUrl = ''
    editForm.abstractReal = ''
    editForm.newsTime = formatDate(new Date())
    editForm.markContent = ''
    editVisible.value = true
}

// 打开编辑弹窗（增加权限校验）
const handleEdit = (row) => {
    if (!isAdminUser.value) {
        ElMessage.warning('仅管理员账号（后缀为-admin)可编辑新闻')
        return
    }
    if (!row) return
    isAdd.value = false
    editForm.id = row.id
    editForm.title = row.title || ''
    editForm.classReal = row.classReal?.toString() || ''
    editForm.siteName = row.siteName || ''
    editForm.sourceUrl = row.sourceUrl || ''
    editForm.abstractReal = row.abstractReal || ''
    editForm.newsTime = row.newsTime || ''
    editForm.markContent = row.markContent || ''
    editVisible.value = true
}

const handleEditClose = () => {
    if (editFormRef.value) {
        editFormRef.value.resetFields()
    }
    editVisible.value = false
}

// 保存编辑/添加（增加权限校验）
const handleSaveEdit = () => {
    if (!isAdminUser.value) {
        ElMessage.warning('仅管理员账号（后缀为-admin）可执行此操作')
        editVisible.value = false
        return
    }
    
    if (!editFormRef.value) return
    
    editFormRef.value.validate((valid) => {
        if (valid) {
            if (isAdd.value) {
                const newNews = {
                    ...editForm,
                    id: generateId(),
                    createTime: formatDate(new Date()),
                    addUser: currentUser.value || '管理员', // 记录当前管理员
                    newsSource: editForm.siteName
                }
                localNewsList.value.push(newNews)
                saveLocalNews()
                ElMessage.success('添加成功')
            } else {
                const index = localNewsList.value.findIndex(item => item.id === editForm.id)
                if (index !== -1) {
                    localNewsList.value[index] = {
                        ...localNewsList.value[index],
                        ...editForm,
                        newsSource: editForm.siteName,
                        addUser: currentUser.value || '管理员' // 更新操作人
                    }
                    saveLocalNews()
                    
                    const publishIndex = toPublishList.value.findIndex(item => item.id === editForm.id)
                    if (publishIndex !== -1) {
                        toPublishList.value[publishIndex] = {
                            ...toPublishList.value[publishIndex],
                            ...editForm,
                            newsSource: editForm.siteName
                        }
                        saveToPublishList()
                        updateToPublishTypeStats()
                    }
                    
                    ElMessage.success('编辑成功')
                } else {
                    ElMessage.warning('只能编辑手动添加的新闻')
                    return
                }
            }
            
            editVisible.value = false
            fetchNews()
        }
    })
}

const handleRowClick = (row, column) => {
    if (!row || column?.label === '操作') return
    
    detailForm.value = {
        title: row.title || '',
        newsSource: row.newsSource || '未知来源',
        newsTime: row.newsTime || '',
        sourceUrl: row.sourceUrl || '',
        abstractReal: row.abstractReal || '',
        markContent: row.markContent || ''
    }
    isAbstractExpanded.value = false
    detailVisible.value = true
}

const handleDetailClose = () => {
    detailForm.value = {
        title: '',
        newsSource: '',
        newsTime: '',
        sourceUrl: '',
        abstractReal: '',
        markContent: ''
    }
    isAbstractExpanded.value = false
    detailVisible.value = false
}

// 右侧待发布功能
const handleAddToPublish = (row) => {
    if (!row) return
    
    const exists = toPublishList.value.some(item => item.id === row.id)
    if (exists) {
        ElMessage.warning(`"${row.title || '该新闻'}"已在待发布列表中`)
        return
    }

    toPublishList.value.unshift({
        ...row,
        addTime: formatDate(new Date()),
        addUser: currentUser.value || '当前用户'
    })

    updateToPublishTypeStats()
    saveToPublishList()
    ElMessage.success(`已将"${row.title || '该新闻'}"加入待发布`)
}

const handleToPublishTypeChange = (classReal) => {
    toPublishType.value = classReal
}

const handleRemoveToPublish = (item) => {
    if (!item) return
    
    toPublishList.value = toPublishList.value.filter(i => i.id !== item.id)
    updateToPublishTypeStats()
    saveToPublishList()
    ElMessage.success(`已移除"${item.title || '该新闻'}"`)
}

// 待发布编辑（增加权限校验）
const handleEditToPublish = (item) => {
    if (!isAdminUser.value) {
        ElMessage.warning('仅管理员账号（后缀为-admin）可编辑新闻')
        return
    }
    if (item) {
        handleEdit(item)
    }
}

// 发布设置跳转
const handleGoToPublishSetting = () => {
    if (toPublishList.value.length === 0) {
        ElMessage.warning('待发布列表为空，无法进入发布设置')
        return
    }
    router.push({
        name: 'newsPublish',
        query: {
            publishList: JSON.stringify(toPublishList.value)
        }
    })
}

// 左侧分页和筛选交互
const handleSearch = () => {
    currentPage.value = 1
    fetchNews()
}

const handleReset = () => {
    keywords.value = ''
    selectedClassReal.value = 'all'
    sortOrder.value = 'desc'
    timeRangeType.value = 'all'
    customTimeRange.value = []
    addMode.value = 'all'
    isPublished.value = 'all'
    currentPage.value = 1
    fetchNews()
}

const handleTypeChange = (classReal) => {
    selectedClassReal.value = classReal
    currentPage.value = 1
    fetchNews()
}

const handleFilterChange = () => {
    currentPage.value = 1
    fetchNews()
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1  // 页码重置为1
    fetchNews()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchNews()
}

const formatAddMode = (row) => {
    return row.addMode === 1 ? '手动' : '自动'
}

const formatPublishStatus = (row) => {
    return row.isPublished === 1 ? '已发布' : '待发布'
}

// 初始化加载（获取当前用户信息）
onMounted(async () => {
    // 实际项目中应从登录状态管理获取用户名
    // 示例：从localStorage获取
    const savedUser = localStorage.getItem('currentUser')
    if (savedUser) {
        currentUser.value = savedUser
    }
    
    loadLocalNews()
    await fetchNews()
    await initToPublishList()
})
</script>

<style scoped>
/* 布局样式 */
.layout-wrapper {
    display: flex;
    gap: 20px;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
}

.left-column,
.right-column {
    height: calc(100vh - 100px);
    box-sizing: border-box;
}

.left-column {
    flex: 3;
}

.right-column {
    flex: 2;
}

.content-wrapper {
    height: 100%;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 24px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    box-sizing: border-box;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* 右侧待发布区域样式 */
.to-publish-header {
    margin-bottom: 16px;
}

.to-publish-title {
    margin: 0 0 15px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.to-publish-type {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 0;
}

.type-tag {
    cursor: pointer;
    background-color: #f4f4f5;
    border-color: #e9e9eb;
    color: #606266;
    transition: all 0.2s;
}

.type-tag:hover {
    background-color: #ecf5ff;
    border-color: #409eff;
    color: #409eff;
}

.active-tag {
    color: #409eff;
    background-color: #ecf5ff;
    border-color: #409eff;
    font-weight: 500;
}

/* 固定高度滚动区 */
.to-publish-scroll-container {
    flex: 1;
    overflow-y: auto;
    padding-right: 8px;
    scrollbar-width: thin;
    scrollbar-color: #c0c4cc #f2f3f5;
}

.to-publish-scroll-container::-webkit-scrollbar {
    width: 6px;
}

.to-publish-scroll-container::-webkit-scrollbar-track {
    background: #f2f3f5;
    border-radius: 3px;
}

.to-publish-scroll-container::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
}

/* 新闻卡片样式 */
.to-publish-card {
    margin-bottom: 12px;
    transition: all 0.2s;
    animation: fadeIn 0.3s ease;
    position: relative;
    padding-top: 24px;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.to-publish-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border-color: #e6f7ff;
}

/* 左上角新闻类型标签 */
.news-type-tag {
    position: absolute;
    top: 0;
    left: 0;
    padding: 2px 8px;
    font-size: 12px;
    color: #fff;
    border-radius: 0 0 4px 0;
    font-weight: 500;
    z-index: 1;
}

.card-header {
    margin-bottom: 8px;
}

.card-title {
    font-size: 15px;
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
}

.card-content {
    font-size: 14px;
    color: #606266;
    line-height: 1.6;
    max-height: 80px;
    overflow: hidden;
    display: -webkit-box;
    margin-bottom: 16px;
}

.card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #909399;
    font-size: 13px;
    padding-top: 10px;
    border-top: 1px dashed #f0f0f0;
}

.footer-info {
    display: flex;
    gap: 15px;
}

.footer-actions {
    display: flex;
    gap: 10px;
}

.remove-btn {
    color: #f56c6c;
}

.remove-btn:hover {
    color: #e4393c;
}

.to-publish-footer {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
}

.publish-setting-btn {
    width: 100%;
}

/* 左侧样式 */
.news-pool-container {
    padding-top: 20px;
    background-color: #fafbfc;
    min-height: calc(100vh - 40px);
}

.page-title {
    margin: 0 0 20px 40px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    padding-left: 10px;
    border-left: 4px solid #409eff;
}

.search-row,
.type-row,
.filter-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

.search-label,
.type-label,
.filter-label {
    margin-right: 12px;
    font-weight: 500;
    color: #606266;
    min-width: 80px;
    text-align: right;
}

.type-row {
    gap: 8px;
}

.highlight-tag {
    color: #409eff;
    background-color: #ecf5ff;
    border-color: #409eff;
}

.default-all-tag {
    color: #409eff;
    background-color: #ecf5ff;
    border-color: #409eff;
}

.el-tag:not(.highlight-tag):not(.default-all-tag) {
    color: #606266;
    background-color: #f4f4f5;
    border-color: #e9e9eb;
}

.el-tag:not(.highlight-tag):not(.default-all-tag):hover {
    color: #409eff;
    background-color: #ecf5ff;
    border-color: #409eff;
}

.el-table .cell {
    white-space: nowrap;
}

.pagination-container {
    margin-top: 20px;
}

.custom-time-display {
    padding: 8px 12px;
    background-color: #f0f9ff;
    border: 1px solid #bae0ff;
    border-radius: 4px;
    margin-bottom: 16px;
}

.time-display-label {
    font-weight: 500;
    color: #1890ff;
}

.time-display-value {
    color: #096dd9;
    margin-left: 4px;
}

.custom-time-picker {
    padding: 20px;
}

.time-tip {
    margin-top: 12px;
    font-size: 12px;
    color: #909399;
    margin-bottom: 0;
}

/* 弹窗样式 */
.edit-dialog-full,
.detail-dialog-full {
    padding: 0 !important;
    margin: 0 !important;
    width: 100% !important;
    height: 100% !important;
    top: 0 !important;
    left: 0 !important;
    display: block !important;
    background: transparent !important;
    box-shadow: none !important;
}

.custom-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 999;
    cursor: pointer;
}

.edit-content-wrapper,
.detail-content-wrapper {
    position: fixed;
    top: 0;
    right: 0;
    width: 50%;
    height: 100%;
    background-color: #fff;
    z-index: 1000;
    overflow: hidden;
    box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
}

.edit-header,
.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e5e7eb;
    background-color: #fafafa;
}

.edit-header h2,
.detail-header h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.close-btn {
    color: #606266;
    background-color: #f5f5f5;
    border: none;
}

.edit-body {
    padding: 0;
    height: calc(100% - 130px);
    overflow: hidden;
}

.edit-layout {
    display: flex;
    height: 100%;
    width: 100%;
}

.edit-form-container {
    width: 48%;
    padding: 20px;
    overflow-y: auto;
    border-right: 1px solid #e5e7eb;
}

.edit-content-container {
    width: 52%;
    padding: 20px;
    overflow-y: auto;
}

.content-header {
    font-weight: 500;
    padding-bottom: 8px;
    margin-bottom: 15px;
    border-bottom: 1px solid #e5e7eb;
}

.mark-content {
    line-height: 1.6;
    font-size: 14px;
}

.content-pre {
    white-space: pre-wrap;
    word-wrap: break-word;
    margin: 0;
    font-family: inherit;
}

.no-content {
    color: #909399;
    text-align: center;
    padding: 20px 0;
}

.edit-footer {
    padding: 15px 20px;
    border-top: 1px solid #e5e7eb;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    background-color: #fafafa;
}

.detail-body {
    padding: 20px;
    height: calc(100% - 100px);
    overflow-y: auto;
}

.detail-top {
    margin-bottom: 20px;
}

.detail-top h3 {
    margin: 0 0 10px;
    font-size: 16px;
    font-weight: 600;
}

.detail-info {
    display: flex;
    gap: 15px;
    margin-bottom: 10px;
    color: #606266;
    font-size: 14px;
}

.detail-info a {
    color: #409eff;
    text-decoration: none;
}

/* 摘要部分样式 */
.detail-abstract-container {
    position: relative;
    margin-bottom: 15px;
}

.detail-abstract {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    line-height: 1.6;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    transition: all 0.3s ease;
}

.detail-abstract.expanded {
    white-space: normal;
}

.toggle-abstract-btn {
    margin-top: 5px;
    padding: 0;
    color: #409eff;
    font-size: 13px;
}

/* 响应式适配 */
@media (max-width: 1440px) {
    .layout-wrapper {
        flex-direction: column;
    }

    .left-column,
    .right-column {
        width: 100%;
        height: auto;
        margin-bottom: 20px;
    }

    .to-publish-scroll-container {
        max-height: 500px;
    }
}

@media (max-width: 768px) {
    .page-title {
        margin-left: 20px;
    }

    .layout-wrapper {
        padding: 0 10px;
    }

    .search-label,
    .type-label,
    .filter-label {
        min-width: auto;
        margin-bottom: 8px;
    }

    .search-row,
    .type-row,
    .filter-row {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>